import {
  addWebsiteTypeApi,
  updateWebsiteTypeApi,
  deleteWebsiteTypeApi,
  getAllWebsiteTypesByConditionApi,
  getAllMenusApi
} from '@/services'
import { addAndUpdateRoleApi, getAllRolesApi, getRolesPaginationApi, setRoleOffByIdApi } from '@/services/rolesApi'
import { omit, pick } from 'lodash'
import { Button, Card, Form, Icon, InputText, Message, Modal, Page, Select, Switch, Table, Typography } from 'magic-ui-react'
import { ModalHandle } from 'magic-ui-react/dist/Modal/interface'
import { ActionType, ColumnType, TableBaseType } from 'magic-ui-react/dist/Table/interface'
import { useEffect, useRef, useState } from 'react'
import styles from './styles.module.less'
import { TableDataType } from './types'

const RolesManage = () => {

  const modalRef = useRef<ModalHandle>()
  const actionRef = useRef<ActionType>()

  const [form] = Form.useForm()

  const [title, setTitle] = useState('')
  const [options, setOptions] = useState([])
  const columns: ColumnType<TableDataType>[] = [
    {
      title: '角色名称',
      dataKey: 'roleName'
    },
    {
      title: '描述',
      dataKey: 'description'
    },
    {
      title: '开关',
      dataKey: 'off',
      bodyCellRender(column, record, index) {
        return <Switch checked={record.off} onChange={(value) => {
          setRoleOffById(record._id, value)
        }} />
      },
    },
    {
      title: '创建时间',
      dataKey: 'createdTime',
      width: 200,
    },
    {
      title: '更新时间',
      dataKey: 'updateTime',
      width: 200,
    },
    {
      title: '操作',
      width: 200,
      dataKey: 'operation',
      bodyCellRender: (_columns, record) => {
        return (
          <div className='flex gap10'>
            <Button
              type='primary'
              onClick={() => {
                setTitle('编辑')
                modalRef.current?.open()
                setTimeout(() => {
                  form.setFieldsValue(record)
                }, 0)
              }}
            >编辑</Button>
            <Button
              status='error'
              onClick={() => {
                setTitle('删除')
                deleteItem(record)
              }}
            >删除</Button>
          </div>
        )
      }
    },
  ]


  const getOptions = async () => {
    try {
      let res = await getAllMenusApi()
      let newOptions = res.data.map((item: any) => {
        return {
          label: item.title,
          value: item._id,
        }
      })
      setOptions(newOptions)
    } catch (error) {

    }
  }

  const setRoleOffById = async (id: string, off: boolean) => {
    try {
      await setRoleOffByIdApi(id, off);
      Message.success('修改成功');
      actionRef.current?.refresh()
    } catch (error) {

    } finally {
      actionRef.current?.refresh()
    }
  }

  const deleteItem = async (record: any) => {
    try {
      await deleteWebsiteTypeApi([record._id])
      Message.success('删除成功');
      actionRef.current?.refresh()
    } catch (error) {

    }
  }

  const onOK = async () => {
    try {
      const requestData = form.getFields()
      await addAndUpdateRoleApi(
        omit(requestData, [
          'updateTime',
          'createTime',
          'operation',
        ])
      );
      Message.success(`${title}成功`);
      modalRef.current?.close()
      actionRef.current?.refresh()
    } catch (error) {
    }
  }

  useEffect(() => {
    getOptions();
  }, [])

  return (
    <Page className={styles.RolesManage}>
      <Table
        actionRef={actionRef}
        columns={columns}
        search={{
          columns: [
            {
              formItem: {
                name: 'roleName',
                label: '角色名称'
              },
              type: 'text'
            },
            {
              formItem: {
                name: 'description',
                label: '描述'
              },
              type: 'text'
            },
          ]
        }}
        oprationContent={(
          <Card borders={[]}>
            <div>
              <Button
                type='primary'
                icon={<Icon icon="add" />}
                onClick={() => {
                  setTitle('添加')
                  modalRef.current?.open()
                }}
              >
                添加
              </Button>
            </div>
          </Card>
        )}
        data={async (pagination, search) => {
          let list: any[] = []
          try {
            const res = await getRolesPaginationApi({
              ...pagination,
              ...search,
            });
            list = res.data
            return {
              list,
              total: res.total!,
            }
          } catch (error) {
          }
        }}
        pagination={{
          sort: ['page'],
        }}
      />
      <Modal title={title} onOK={onOK} ref={modalRef}>
        <Form
          form={form}
          layout='vertical'
          initialValues={{
            limits: []
          }}
        >
          <Form.Item label="类型名称" name='roleName'>
            <InputText />
          </Form.Item>
          <Form.Item label="类型描述" name='description'>
            <InputText />
          </Form.Item>
          <Form.Item label="开关" name='off'>
            <div>
              <Switch />
            </div>
          </Form.Item>
          <Form.Item label="菜单权限" name='limits'>
            <Select
              options={options}
              multiple
            />
          </Form.Item>
        </Form>
      </Modal>
    </Page>
  )
}
export default RolesManage